package com.ponhu.ea2.stockcenter.provider.service.entity.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ponhu.ea2.stockcenter.enums.ResponseCodeEnum;
import com.ponhu.ea2.stockcenter.provider.entity.StockWarehouseChange;
import com.ponhu.ea2.stockcenter.provider.entity.StockWarehouseChangeSnapshot;
import com.ponhu.ea2.stockcenter.provider.entity.StockWarehouseRelation;
import com.ponhu.ea2.stockcenter.provider.mapper.StockWarehouseChangeSnapshotMapper;
import com.ponhu.ea2.stockcenter.provider.service.entity.StockWarehouseChangeSnapshotService;
import com.ponhu.ea2.stockcenter.provider.support.exception.StockRuntimeException;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 仓库库存变动快照表服务实现类
 */
@Service
public class StockWarehouseChangeSnapshotServiceImpl
        extends ServiceImpl<StockWarehouseChangeSnapshotMapper, StockWarehouseChangeSnapshot>
        implements StockWarehouseChangeSnapshotService {


    /**
     * 批量保存仓库库存变动快照
     *
     * @param changeList
     * @param stockWarehouseRelations
     * @return
     */
    @Override
    @Transactional
    public boolean saveBatchSnapshots(List<StockWarehouseChange> changeList,
                                      List<StockWarehouseRelation> stockWarehouseRelations) {

        Map<String, StockWarehouseRelation> relationMap = stockWarehouseRelations.parallelStream()
                .collect(Collectors.toMap(StockWarehouseRelation::getInventoryCode, Function.identity()));

        List<StockWarehouseChangeSnapshot> snapshotList = changeList
                .parallelStream().map(change -> new StockWarehouseChangeSnapshot()
                        .setWarehouseChangeId(change.getId())
                        .setInventoryId(change.getInventoryId())
                        .setInventoryCode(change.getInventoryCode())
                        .setWarehouseCode(relationMap.get(change.getInventoryCode()).getWarehouseCode())
                        .setRealStockNum(relationMap.get(change.getInventoryCode()).getRealStockNum())
                        .setAvailableStockNum(relationMap.get(change.getInventoryCode()).getAvailableStockNum())
                        .setLockedStockNum(relationMap.get(change.getInventoryCode()).getLockedStockNum()))
                .collect(Collectors.toList());

        if (BooleanUtils.isNotTrue(saveBatch(snapshotList))) {
            throw new StockRuntimeException(
                    ResponseCodeEnum.STOCK_WAREHOUSE_EXCEPTION_900104);
        }

        return true;
    }

}




